﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Package;
using Microsoft.VisualStudio.TextManager.Interop;
using LuaLanguage.Integration;

namespace LuaLanguage.UserSupplied
{
    public class TypeAndMemberDropdownBars : Microsoft.VisualStudio.Package.TypeAndMemberDropdownBars
    {
        private List<MemberDefinition> _members;

        public TypeAndMemberDropdownBars(LanguageService service): base(service)
        {
        }

        public override bool OnSynchronizeDropdowns(LanguageService languageService, Microsoft.VisualStudio.TextManager.Interop.IVsTextView textView, int line, int col, System.Collections.ArrayList dropDownTypes, System.Collections.ArrayList dropDownMembers, ref int selectedType, ref int selectedMember)
        {
            bool bChanged = false;
            LuaLanguage.Source source = languageService.GetSource(textView) as LuaLanguage.Source;
            if (source != null)
            {
                if(source.Members != _members)
                {
                   dropDownTypes.Clear();

                   if (source.Members != null)
                   {
                       var sortedMembers = source.Members.OrderBy(m => m.Name);
                       foreach (var member in sortedMembers)
                       {
                           var dropDownMember = new DropDownMember(member.Name, member.Span, member.IconIndex, DROPDOWNFONTATTR.FONTATTR_PLAIN);
                           dropDownTypes.Add(dropDownMember);
                       }
                   }

                   _members = source.Members;

                   bChanged = true;
                }   
                
                if(_members != null)
                {
                    for(int i = 0; i < _members.Count; i++)
                    {
                        var member = _members[i];
                        var span = member.Span;

                        if(span.iStartLine < line || (span.iStartLine == line && span.iStartIndex <= col))
                        {
                            if (span.iEndLine > line || (span.iEndLine >= line && span.iEndIndex >= col))
                            {
                                selectedType = i;
                                bChanged = true;
                            }
                        }
                    }
                } 
            }

            return bChanged;
        }
    }
}
